package edu.ptu.springboot04.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.ptu.springboot04.common.controller.AjaxResponse;
import edu.ptu.springboot04.domain.entity.User;
import edu.ptu.springboot04.domain.query.LoginQuery;
import edu.ptu.springboot04.mapper.UserMapper;
import edu.ptu.springboot04.service.IUserService;
import edu.ptu.springboot04.utils.JWTUtil;
import edu.ptu.springboot04.utils.LoginUser;
import edu.ptu.springboot04.utils.RedisUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @BelongsProject: springboot04
 * @BelongsPackage: edu.ptu.springboot04.service.impl
 * @Author: HYJ
 * @CreateTime: 2025-03-22  00:07
 * @Description: TODO
 * @Version: 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public AjaxResponse login(LoginQuery user) {

        UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());

        Authentication authenticate = authenticationManager.authenticate(token);

        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }

        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        String jwt = JWTUtil.generateToken(loginUser.getUser().getUserId(), loginUser.getUser().getUsername());

        redisUtil.setCacheObject("login:" + loginUser.getUser().getUserId(), loginUser);
        return AjaxResponse.success("登录成功", jwt);
    }
}
